package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import butterknife.BindView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BasePagerActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.EmojiFilter;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.AttendanceDetail;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.Success;
import com.isunland.managesystem.receiver.AlarmReceiver;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.RevealBackgroundView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

@SuppressWarnings({ "deprecation", "DanglingJavadoc" }) public class NewAttendanceDetailFragment
    extends BaseFragment {
  private static final int TAKE_PHOTO = 0;

  public AMapLocationClient mLocationClient;  //高德定位
  @BindView(R.id.tv_nunomal_attendacedetail) TextView mUnNormalTv;//不正常打卡
  @BindView(R.id.tv_signInfo_attendacedetail) TextView mSignInfoTv;//签到信息
  @BindView(R.id.vRevealBackground) RevealBackgroundView vRevealBa1ckground;
  @BindView(R.id.bt_sign_in) Button mBtSignIn;
  @BindView(R.id.bt_sign_out) Button mBtSignOut;
  @BindView(R.id.bt_sign_keep) Button mBtSignKeep;
  @BindView(R.id.et_remark_attendanceDetail) EditText mEtRemarkAttendanceDetail;
  @BindView(R.id.ib_photo_attendanceDetail) ImageButton mIbPhotoAttendanceDetail;
  @BindView(R.id.iv_picture_attendanceDetail) ImageView mIvPictureAttendanceDetail;
  @BindView(R.id.tv_location_attendanceDetail) TextView mRefreshLocationTv;
  @BindView(R.id.rb_gps) RatingBar mRatingBar;
  @BindView(R.id.tv_gps) TextView mTvGPS;
  @BindView(R.id.tv_hintWifi) TextView mTvHintWifi;
  private MyProgressDialog mDialog;

  //private PullToRefreshScrollView mSvRefresh;

  private Callbacks mCallbacks;
  private File mCameraFile;

  private AttendanceDetail mItem;
  private GeocodeSearch mSearch;

  @Override public void onAttach(Context activity) {
    super.onAttach(activity);
    mCallbacks = (Callbacks) activity;
  }

  @Override public void initData() {
    super.initData();
    mLocationClient = initLocationClient();
    mItem = new AttendanceDetail();
    mItem.setAttendIdentifyNumber(MyUtils.getDeviceId(mActivity));
    mItem.setPhoneIdentifyNumber(mCurrentUser.getPhoneIdentifyNumber());
    mItem.setWifiInfo(MyUtils.getWifiParams(MyUtils.getWifiInfo(mActivity)));
    mSearch = new GeocodeSearch(mActivity);
    // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系

    mSearch.setOnGeocodeSearchListener(new MySearchListener());
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(R.string.sign_everyday);
    getLocation();
    mBtSignKeep.setText(getRefreshText(AlarmReceiver.isServiceAlarmOn(mActivity)));
    mTvHintWifi.setText(getHintMessage());
    //mRefreshLocationTv.setText(getString(R.string.isrefreshingLoaction));
    mIbPhotoAttendanceDetail.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        takePhoto();
      }
    });
    mIvPictureAttendanceDetail.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        if (mCameraFile == null) return;
        Intent intent = new Intent(mActivity, AttendanceDetailBigPhotoActivity.class);
        intent.putExtra(AttendanceDetailBigPhotoFragment.FILE_DIR, mCameraFile.getAbsolutePath());
        startActivity(intent);
      }
    });
    mBtSignIn.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        mItem.setSignType(AttendanceDetail.SIGN_IN);
        mItem.setSignTypeName(getString(R.string.sign_in));
        mItem.setSignStatus(AttendanceDetail.SIGN_NOT_START);
        //动画开始
        startAnim(v);
        sign(true, true);
      }
    });
    mBtSignOut.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        mItem.setSignType(AttendanceDetail.SIGN_OUT);
        mItem.setSignTypeName(getString(R.string.sign_out));
        mItem.setSignStatus(AttendanceDetail.SIGN_NOT_START);
        //动画开始
        startAnim(v);
        sign(true, true);
      }
    });
    mBtSignKeep.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //启用或关闭外勤自动记录轨迹
        //如果当前是关闭状态,启动服务
        if (!AlarmReceiver.isServiceAlarmOn(mActivity)) {
          mItem.setSignType(AttendanceDetail.SIGN_KEEP);
          mItem.setSignTypeName(getString(R.string.sign_keep));
          mItem.setSignStatus(AttendanceDetail.SIGN_NOT_START);
          //每次启动重新生成id,在本次打卡和后台服务中使用同一个id.用于地图轨迹,标记为同一个
          SharedPreferencesUtil.setString(mActivity, SharedPreferencesUtil.OUT_ID,
              UUID.randomUUID().toString());
          //外勤记录更新时间间隔,避免与service重复打卡.
          SharedPreferencesUtil.setLong(mActivity, SharedPreferencesUtil.LAST_AUTO_SIGN_MILLIS,
              System.currentTimeMillis());
          //动画开始
          startAnim(v);
          sign(true, true);
        }
        AlarmReceiver.setServiceAlarm(mActivity,
            !AlarmReceiver.isServiceAlarmOn(mActivity));  //启动或关闭后台定位服务
        mBtSignKeep.setText(getRefreshText(AlarmReceiver.isServiceAlarmOn(mActivity))); //刷新按钮文本
      }
    });

    mRefreshLocationTv.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        //只有点击的时候显示提示,所以设置标识.
        mItem.setClickrefresh(false);
        getLocation();
      }
    });
    vRevealBa1ckground.setOnStateChangeListener(new RevealBackgroundView.OnStateChangeListener() {
      @Override public void onStateChange(int state) {
        LogUtil.i("state=" + state);
        if (RevealBackgroundView.STATE_FINISHED == state) {

          vRevealBa1ckground.setToStartFrame();
          vRevealBa1ckground.setVisibility(View.INVISIBLE);
          mItem.setAnim(true);
          refreshWhenAnimEnd();
        }
      }
    });
    volleyPostUnNormal();
  }

  private void startAnim(View v) {
    mItem.setAnim(false);
    vRevealBa1ckground.setFillPaintColor(((ColorDrawable) v.getBackground()).getColor(), 101);
    vRevealBa1ckground.setVisibility(View.VISIBLE);
    vRevealBa1ckground.startFromLocation(getViewLocation(v));
  }

  /** 初始化高德定位客户端,进行初始化配置 */
  private AMapLocationClient initLocationClient() {
    AMapLocationClient locationClient = new AMapLocationClient(MyApplication.getAppContext());
    locationClient.setLocationListener(new MyLocationListener());
    //初始化定位参数
    AMapLocationClientOption locationClientOption = new AMapLocationClientOption();
    //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
    locationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
    //设置是否返回地址信息（默认返回地址信息）
    locationClientOption.setNeedAddress(true);
    //设置是否强制刷新WIFI，默认为强制刷新
    //noinspection deprecation
    locationClientOption.
        setWifiActiveScan(true);
    //设置是否允许模拟位置,默认为false，不允许模拟位置
    locationClientOption.setMockEnable(false);
    locationClientOption.setLocationCacheEnable(false);
    //设置是否只定位一次,默认为false
    locationClientOption.setOnceLocation(false);
    //设置定位间隔,单位毫秒,默认为2000ms,设置之后startLocation经过间隔时间才返回结果.
    locationClientOption.setInterval(1000 * 30);
    //给定位客户端对象设置定位参数
    locationClient.setLocationOption(locationClientOption);
    return locationClient;
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_new_attendance_detail;
  }

  @Override public void onDestroy() {

    if (null != mLocationClient) {
      /**
       * 如果AMapLocationClient是在当前Activity实例化的，
       * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
       */
      mLocationClient.onDestroy();
      mLocationClient = null;
    }
    super.onDestroy();
  }

  @Override public void onDetach() {
    super.onDetach();
    mCallbacks = null;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_offline, menu);

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        Intent intent = GuideMenuNewActivity.newIntent(mActivity);
        startActivity(intent);
        return true;
      case R.id.menu_item_offline:
        Intent offlineIntent = new Intent(mActivity, AttendanceOutlineActivity.class);
        offlineIntent.putExtra(AttendanceOutlineListFragment.EXTRA_IS_LOGIN, true);
        startActivity(offlineIntent);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == TAKE_PHOTO) {
      if (mCameraFile == null) {
        ToastUtil.show(R.string.getPhotoFailed);
        return;
      }

      Bitmap bitmap = BitmapFactory.decodeFile(mCameraFile.getAbsolutePath());
      if (bitmap == null) {
        ToastUtil.show(R.string.getPhotoFailed);
        mCameraFile = null;
        return;
      }
      Bitmap mNewBitmap = ImageTools.zoomBitmap(bitmap, 400, 400);
      bitmap.recycle();
      mCameraFile = ImageTools.savePhotoToSDCard(mNewBitmap, FileUtil.getFileDir(),
          System.currentTimeMillis() + "");
      // startPhotoZoom(Uri.fromFile(mCameraFile));
      mIvPictureAttendanceDetail.setImageBitmap(mNewBitmap);
      mIvPictureAttendanceDetail.setVisibility(View.VISIBLE);
    }
    // if (requestCode == SURE_SIGN) {
    // volleyPostSign();
    // }
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   */
  private void getLocation() {
    //获取位置,如果是第一次进入,显示dialog.
    if (!mItem.isFirstRefresh()) {
      mItem.setFirstRefresh(true);
      mDialog = MyProgressDialog.newInstence(getString(R.string.isrefreshingLoaction));
      showDialog(mDialog, 0);
    }
    ToastUtil.show(R.string.isrefreshingLoaction);
    mLocationClient.stopLocation();
    mTvHintWifi.setText(getHintMessage());
    mLocationClient.startLocation();    //启动定位
  }

  /** 打卡,判断位置是否有效 */
  private void sign(boolean isNeedLoction, boolean isNeedGenerate) {
    if (isNeedLoction && (!mItem.isLocationValid())) {
      showLocationDialog();
      return;
    }
    if (isNeedGenerate && mItem.isGenerateValid()) {
      showGenerateSignDialog();
      return;
    }
    volleyPostSign();
  }

  private void showGenerateSignDialog() {
    //0-9点签退补打卡.
    new AlertDialog.Builder(mActivity).setTitle(R.string.hintMessage)
        .setMessage(R.string.generate_yesterday_checkout)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            mItem.setIfReplenish(AttendanceDetail.IF_REPUBLISH_TRUE);
            sign(false, false);
          }
        })
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            sign(false, false);
          }
        })
        .show();
  }

  private void showLocationDialog() {
    //位置无效,提示是否继续打卡.
    new AlertDialog.Builder(mActivity).setTitle(R.string.restart_title)
        .setMessage(R.string.sure_sign)
        .setPositiveButton("设置权限", new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            Uri packageURI = Uri.parse("package:" + mActivity.getPackageName());
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
            startActivity(intent);
          }
        })
        .setNegativeButton("继续打卡", new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            sign(false, true);
          }
        })
        .show();
  }

  private int[] getViewLocation(View v) {
    int[] startingLocation = new int[2];
    v.getLocationOnScreen(startingLocation);
    startingLocation[0] += v.getWidth() / 2;
    int statusBar = getStatusBar();

    startingLocation[1] =
        startingLocation[1] + v.getHeight() / 2 - ((BasePagerActivity) mActivity).getTabLayout()
            .getHeight() - ((BasePagerActivity) mActivity).getAppBar().getHeight() - statusBar;

    return startingLocation;
  }

  private int getStatusBar() {
    //屏幕
    DisplayMetrics dm = new DisplayMetrics();
    mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    //应用区域
    Rect outRect1 = new Rect();
    mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
    return dm.heightPixels - outRect1.height();
  }

  /**
   * 获取不正常打卡数据
   */
  private void volleyPostUnNormal() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SIGN_UNNORMAL);
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode());
    params.put("staffId", CurrentUser.newInstance(mActivity).getJobNumber());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        //                hintUnNormal(21);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          int days = Integer.parseInt(arg0);
          if (days > 0) {
            hintUnNormal(days);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      @Override public boolean ifToastError() {
        return false;
      }
    });
  }

  /**
   * 提示异常打卡天数
   *
   * @param days 天数
   */
  private void hintUnNormal(int days) {
    String unnormalStr = getString(R.string.hint_unnormal_sign, days + "");
    mUnNormalTv.setVisibility(View.VISIBLE);
    mUnNormalTv.setText(unnormalStr);
  }

  //private void volleyPostSign() {
  //    volleyPostSign(false);
  //}

  private void volleyPostSign() {

    ParamsNotEmpty params = new ParamsNotEmpty();

    params.put("latitude", mItem.getLatitude());
    params.put("longitude", mItem.getLongitude());
    params.put("location",
        MyStringUtil.isEmpty(mItem.getLocation()) ? getString(R.string.noLocation)
            : mItem.getLocation());
    params.put("checkType", mItem.getSignType());
    params.put("attendIdentifyNumber", mItem.getAttendIdentifyNumber());//本机id
    params.put("phoneIdentifyNumber", mItem.getPhoneIdentifyNumber());//服务端保存的绑定的id.
    params.put("wifiInfo", mItem.getWifiInfo()); //0-9点自动生成记录,11:59的签退,00:01的签到.
    params.put("ifReplenish", mItem.getIfReplenish());
    params.put("remark", EmojiFilter.filterEmoji(MyStringUtil.getText(mEtRemarkAttendanceDetail)));
    //是否上传图片
    params.put("hasImage",
        (mCameraFile != null && mCameraFile.exists()) ? AttendanceDetail.HAS_IMAGE_TRUE
            : AttendanceDetail.HAS_IMAGE_FALSE);
    //外勤传递outid,用于标识同一条外勤.
    if (MyStringUtil.equals(AttendanceDetail.SIGN_KEEP, mItem.getSignType())) {
      params.put("outId",
          SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.OUT_ID, ""));
    }
    mItem.setSignStatus(AttendanceDetail.SIGN_START);
    mActivity.volleyPost(ApiConst.getAbsoluteUrl(ApiConst.URL_SIGN), params.getParams(),
        new VolleyResponse() {

          @Override public void onVolleyResponse(String arg0) throws JSONException {

            dismissDialogLoading();
            Success original = new Gson().fromJson(arg0, Success.class);
            //设置id,用于长传附件图片
            mItem.setId(original.getId());
            if (original.getSuccess() != 1) {
              showErrorDialog(original.getMsg());
              return;
            }
            if (original.getIsValid() != 1) {
              showErrorDialog(original.getMsg());
            }
            ToastUtil.show(original.getMsg());
            // 上传图片
            volleyPostImage();
            //可跳转刷新
            mItem.setSignStatus(AttendanceDetail.SIGN_FINISH);
            refreshWhenAnimEnd();
            mEtRemarkAttendanceDetail.setText("");
          }

          @Override public void onVolleyError(VolleyError arg0) {

            dismissDialogLoading();
            // Toast.makeText(mActivity,
            // R.string.failure_operation,
            // Toast.LENGTH_SHORT).show();
            ToastUtil.show(R.string.failure_operation);
          }
        });
  }

  /** 是有当动画结束并且volley打卡结束后才跳转 */
  private void refreshWhenAnimEnd() {
    if (AttendanceDetail.SIGN_START == mItem.getSignStatus()) {
      mDialog = MyProgressDialog.newInstence(getString(R.string.loadingSign));
      showDialog(mDialog, 0);
    }
    if (mItem.isAnim() && mItem.getSignStatus() == AttendanceDetail.SIGN_FINISH) {
      mCallbacks.onRefresh();//动画结束,打卡结束,可跳转页面.
    }
  }

  private void volleyPostImage() {
    LogUtil.i("file=" + mCameraFile);
    if (mCameraFile == null) {
      return;
    }
    if (!MyUtils.isNetLink(mActivity)) {
      // Toast.makeText(mActivity, R.string.network_error,
      // Toast.LENGTH_SHORT).show();
      ToastUtil.show(R.string.network_error);
      return;
    }

    RequestParams params2 = new RequestParams("id", mItem.getId());
    try {
      params2.put("secret_passwords", mCameraFile);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      ToastUtil.show(R.string.fileNotFound);
      return;
    }
    //InputStream myInputStream = null;
    //try {
    //    myInputStream = new FileInputStream(mCameraFile);
    //} catch (FileNotFoundException e) {
    //
    //    LogUtil.e("errorLog", e);
    //    // Toast.makeText(mActivity, R.string.fileNotFound,
    //    // Toast.LENGTH_SHORT).show();
    //    ToastUtil.show(R.string.fileNotFound);
    //}
    //if (myInputStream != null) {
    //
    //    params2.put("secret_passwords", myInputStream, "image.jpg");
    //}

    DefaultAsyncHttpClient.post(ApiConst.URL_SIGN_IMAGE, params2, new AsyncHttpResponseHandler() {
      @Override public void onStart() {
        // Toast.makeText(mActivity,
        // R.string.isUploadingImage,
        // Toast.LENGTH_SHORT).show();
        ToastUtil.show(R.string.isUploadingImage);
      }

      @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        LogUtil.i("response=" + new String(response));
        // Toast.makeText(mActivity,
        // R.string.fileUploadSuccess,
        // Toast.LENGTH_SHORT).show();
        //清空
        mIvPictureAttendanceDetail.setVisibility(View.GONE);
        mCameraFile = null;
        //上传图片成功后刷新列表
        if (mActivity != null && isVisible()) {
          mCallbacks.onRefresh();
        }
        ToastUtil.show(R.string.fileUploadSuccess);
      }

      @Override
      public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        LogUtil.e("statusecode=" + statusCode + ",文件上传失败", e);
        // Toast.makeText(mActivity,
        // R.string.fileUploadFailure,
        // Toast.LENGTH_SHORT).show();
        ToastUtil.show(R.string.fileUploadFailure);
      }

      @Override public void onRetry(int retryNo) {
      }
    });
  }

  private Spanned getHintMessage() {
    StringBuilder hintStr = new StringBuilder();
    hintStr.append(getString(R.string.hintHtml));
    if (!MyUtils.isNetLink(mActivity)) {
      hintStr.append(getString(R.string.network_error));
    } else if (!MyUtils.isWifiEnabled(mActivity)) {
      hintStr.append(getString(R.string.hintOpenWifi));
    } else {
      hintStr.append(getString(R.string.hintRefreshLocation));
    }
    return Html.fromHtml(hintStr.toString());
  }

  /**
   * 刷新外勤按钮的的文本
   */
  private String getRefreshText(boolean isServiceAlarmOn) {
    //是否启动了外勤自动记录轨迹.
    return isServiceAlarmOn ? getString(R.string.sign_keep_off) : getString(R.string.sign_keep);
  }

  private void takePhoto() {

    if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

      mCameraFile = new File(FileUtil.getFileDir(), System.currentTimeMillis() + ".jpg");
      //noinspection ResultOfMethodCallIgnored
      mCameraFile.getParentFile().mkdirs();

      Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCameraFile));
      startActivityForResult(intent2, TAKE_PHOTO);
    } else {
      // Toast.makeText(mActivity, R.string.check_sd_card,
      // Toast.LENGTH_SHORT).show();
      ToastUtil.show(R.string.check_sd_card);
    }
  }

  private void dismissDialogLoading() {

    try {
      mDialog.dismiss();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected void showErrorDialog(String message) {
    //如果loadingDialog在显示,隐藏
    //if ((mDialog!=null)&&mDialog.isVisible())mDialog.dismiss();
    mItem.setSignStatus(AttendanceDetail.SIGN_ERROR);
    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity).setMessage(message)
        .setTitle("提示")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            // Auto-generated method stub

          }
        });
    builder.create().show();
  }

  private void updateRating(int gpsAccuracy) {
    switch (gpsAccuracy) {
      case AMapLocation.GPS_ACCURACY_GOOD:
        mRatingBar.setRating(3);
        mTvGPS.setText("强");
        break;
      case AMapLocation.GPS_ACCURACY_BAD:
        mRatingBar.setRating(2);
        mTvGPS.setText("弱");
        break;
      case AMapLocation.GPS_ACCURACY_UNKNOWN:
        mRatingBar.setRating(0);
        mTvGPS.setText("无");
        break;
    }
  }

  /**
   * 更新今日签到,签退信息
   */
  protected void updateSignInfo(Date in, Date out) {
    StringBuilder sb = new StringBuilder();
    if (in == null) {
      sb.append(" <font color='#d71345'>今日未签到</font>");
    } else {
      sb.append(" <font color='blue'>签到 ").append(DateFormat.format("kk:mm", in)).append("</font>");
    }
    if (out == null) {
      sb.append("  <font color='#d71345'>未签退</font>");
    } else {
      sb.append("  <font color='blue'>签退 ")
          .append(DateFormat.format("kk:mm", out))
          .append("</font>");
    }
    mSignInfoTv.setVisibility(View.VISIBLE);
    CharSequence charSequence = Html.fromHtml(sb.toString());
    mSignInfoTv.setText(charSequence);
  }

  private void updateLocation(double lat, double lon, String addr) {

    // 地理信息编码.
    mItem.setLatitude(MyStringUtil.valueOf(lat));
    mItem.setLongitude(MyStringUtil.valueOf(lon));
    mItem.setLocation(addr);
    //只有用户点击刷新的时候提示.
    if (!mItem.isClickrefresh()) {
      mItem.setClickrefresh(true);
      ToastUtil.show(mItem.getLocation());
    }
    mRefreshLocationTv.setText(mItem.getLocation());
  }

  public interface Callbacks {
    void onRefresh();
  }

  private class MyLocationListener implements AMapLocationListener {

    @Override public void onLocationChanged(final AMapLocation location) {
      if (location == null || location.getErrorCode() != 0) {
        dismissDialogLoading();
        mRefreshLocationTv.setHint(R.string.noLocation);
        mItem.setLatitude(AttendanceDetail.ZERO);
        mItem.setLongitude(AttendanceDetail.ZERO);
        mItem.setLocation(AttendanceDetail.EMPTY);
        return;
      }

      updateRating(location.getGpsAccuracyStatus());
      //如果有位置信息,直接用.
      if (!MyStringUtil.isEmpty(location.getAddress())) {
        String province = location.getProvince();//北京市
        String city = location.getCity();//
        String district = location.getDistrict();//海淀区
        String street = location.getStreet();//上地五街
        String building = location.getPoiName();//昊海大厦
        if (MyStringUtil.equals(province, city)) province = "";
        String address = MyStringUtil.connect(province, city, district, street, building);
        dismissDialogLoading();
        updateLocation(location.getLatitude(), location.getLongitude(), address);
      } else {
        //gps 搜索,如果有位置信息就不搜索,因为他不稳定,不是每次都有位置信息的.
        mSearch.getFromLocationAsyn(
            new RegeocodeQuery(new LatLonPoint(location.getLatitude(), location.getLongitude()),
                200, GeocodeSearch.AMAP));
      }
    }
  }

  private class MySearchListener implements GeocodeSearch.OnGeocodeSearchListener {

    @Override public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
      dismissDialogLoading();
      //返回结果成功或者失败的响应码。1000为成功，其他为失败
      if (rCode == 1000) {
        if (result != null
            && result.getRegeocodeAddress() != null
            && result.getRegeocodeAddress().getFormatAddress() != null) {
          RegeocodeAddress address = result.getRegeocodeAddress();
          double lat = result.getRegeocodeQuery().getPoint().getLatitude();
          double lon = result.getRegeocodeQuery().getPoint().getLongitude();
          String province = address.getProvince();//北京市
          String city = address.getCity();//
          String district = address.getDistrict();//海淀区
          String street = (address.getStreetNumber() == null) ? ""
              : address.getStreetNumber().getStreet();//上地五街
          String building = ((address.getAois() == null) || (address.getAois().get(0) == null)) ? ""
              : address.getAois().get(0).getAoiName();//昊海大厦
          if (MyStringUtil.equals(province, city)) province = "";
          String addr = MyStringUtil.connect(province, city, district, street, building);
          updateLocation(lat, lon, addr);
        }
      }
    }

    @Override public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
  }
}

